package com.tlgen.orm.components.dataSource;

import com.tlgen.orm.annotation.DataSource;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.stereotype.Component;

@Aspect
@Component
public class DataSourceAspect {

    @Around("@within(dataSource) || @annotation(dataSource)")
    public Object switchDataSource(ProceedingJoinPoint pjp, DataSource dataSource) throws Throwable {
        // 获取最终使用的数据源名称
        String dsName = resolveDataSourceName(pjp, dataSource);

        // 在指定数据源上下文中执行
        return DataSourceContextHolder.executeInContext(dsName, () -> {
            try {
                return pjp.proceed();
            } catch (Throwable e) {
                throw new RuntimeException(e);
            }
        });
    }

    private String resolveDataSourceName(ProceedingJoinPoint pjp, DataSource annotation) {
        if (annotation != null) {
            return annotation.value();
        }

        // 检查类级别注解
        Class<?> targetClass = pjp.getTarget().getClass();
        DataSource classAnnotation = AnnotationUtils.findAnnotation(targetClass, DataSource.class);
        if (classAnnotation != null) {
            return classAnnotation.value();
        }

        // 默认返回主数据源
        return "master_db";
    }

}